import secrets

from fastapi import FastAPI, Request, Response

from models import Product, User, UserCookie, UserCreate

app = FastAPI()

# Пример пользовательских данных (для демонстрационных целей) 
fake_users = {
    1: {"username": "john_doe", "email": "john@example.com"},
    2: {"username": "jane_smith", "email": "jane@example.com"},
}

# Конечная точка для получения информации о пользователе по ID
@app.get("/users/")
def read_user(limit: int = 10):
    return dict(list(fake_users.items())[:limit])


@app.post("/feedback/")
def set_user(user: User):
    print(user)
    fake_users[3] = {user.name}
    print(fake_users)
    return f"Feedback received. Thank you, {user.name}!"


@app.post("/create_user/")
def set_user_info(user: UserCreate):
    return user

products = []

@app.post("/products/")
async def create_products(product_list: list[Product]):
    for product in product_list:
        products.append(product)
    return products

@app.get("/product/{product_id}/") 
async def get_product(product_id: int) -> Product:
    for product in products:
        if product.product_id == product_id:
            return product
        

@app.get("/products/search/")
async def get_search_products(keyword: str = '', category: str = '', limit: int = 5):
    # prod = []
    # for product in products:
    #     if product.category == category:
    #         prod.append(product)
    # return prod[:limit]
    res = list(filter(lambda product: keyword in product.name, products))
    result = list(filter(lambda product: category in product.category, res))
    return result

# Cookie
users = {}
@app.post("/login")
async def create_user_cookie(user: UserCookie, response: Response):
    token = secrets.token_urlsafe(16)
    users[user.username] = token
    response.set_cookie(key='session_token', value=token)
    return {'session_token': 'done'}

@app.get("/user/")
async def get_token(response: Response):
    for u in users:
        return {'session_token': users[u]}